/**
 * Copyright (c) 2011, Jason Gardner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.freecake.bonejams;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

import org.freecake.bonejams.model.Mp3File;

import org.cmc.music.metadata.ImageData;
import org.cmc.music.metadata.IMusicMetadata;
import org.cmc.music.metadata.MusicMetadata;
import org.cmc.music.metadata.MusicMetadataSet;
import org.cmc.music.myid3.MyID3;

public class PlaybackView extends Activity implements OnSeekBarChangeListener {
    
    private MediaPlayer mediaPlayer;
    private boolean seeking = false;
    private ArrayList songQueue = null;
    private ArrayList origQueue = null;
    private int currentSongIdx = -1;
    private Mp3File currentSong = null;
    private int currentRating = 0;
    
    private boolean shuffle = true;
    
    protected Handler statusHandler;    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.player_main);
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(songCompletedListener);            
            
            addButtonHandlers();
                
            //start screen refresh thread
            statusHandler = new Handler();
            statusHandler.postAtTime(screenRefresh, 1000);
            
            Bundle extras = getIntent().getExtras();
            ArrayList songlist = ((BoneJamsApplication) this.getApplication()).getCurrentSongList();
            if (songlist != null) {
                queueSongs(songlist);
                updateTitle();
                playPause();
            }
        }        
    }
    
    private void addButtonHandlers() {
        
        ((Button) this.findViewById(R.id.btn_play))
            .setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        playPause();
                    }
            });
            
        ((Button) this.findViewById(R.id.btn_back))
            .setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        previous();
                    }
            });        
            
        ((Button) this.findViewById(R.id.btn_forward))
            .setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        next();
                    }
            });                    
            
        ((Button) this.findViewById(R.id.btn_shuffle))
            .setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        toggleShuffle();
                    }
            });        

        ((ImageView) this.findViewById(R.id.player_albumImage))
            .setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        showDialog(0);
                    }
            });            
    }
    
    public void queueSongs(ArrayList v) {
        songQueue = (ArrayList) v.clone();
        if (shuffle == true) {
            shuffleQueue();            
        }
        origQueue = (ArrayList) v.clone();
    }
    
    private void shuffleQueue() {
        int i,rand;
        Object temp;
        Random random = new Random(System.currentTimeMillis());
        for (i = 0; i < songQueue.size(); i++) {
            rand = (random.nextInt() & 0x7FFFFFFF) % songQueue.size();
            temp = songQueue.get(i);
            songQueue.set(i, songQueue.get(rand));
            songQueue.set(rand, temp);
        }         
    }
    
    //toggle play/pause state
    private void playPause() {
        if (currentSongIdx == -1) {
            ((Button) this.findViewById(R.id.btn_play))
                .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.btn_pause));
            currentSongIdx = 0;
            play();
        } else {
            if (mediaPlayer.isPlaying()){
                ((Button) this.findViewById(R.id.btn_play))
                    .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.btn_play));
                mediaPlayer.pause();
            } else {
                ((Button) this.findViewById(R.id.btn_play))
                    .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.btn_pause));
                mediaPlayer.start();                    
            }
        }        
    }
    
    //go to the previous song or restart current song
    private void previous() {
        if (currentSongIdx != -1) {
            if (mediaPlayer.getCurrentPosition() < 5000) {
                currentSongIdx--;
                if (currentSongIdx == -1) {
                    currentSongIdx = songQueue.size() - 1;      
                }   
                play();
            } else {
                mediaPlayer.seekTo(0);
            }
        }
    }
    
    //go to the next song
    private void next() {
        if (currentSongIdx != -1) {
            currentSongIdx++;
            if (currentSongIdx == songQueue.size()) {
                currentSongIdx = 0;      
            }
            play();
        }
    }    
    
    //toggle shuffle
    private void toggleShuffle() {
        if (shuffle == true) {
            shuffle = false;
            songQueue = (ArrayList) origQueue.clone();
            ((Button) this.findViewById(R.id.btn_shuffle))
                .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.btn_shuffle));               
        } else {
            shuffle = true;
            shuffleQueue();
            ((Button) this.findViewById(R.id.btn_shuffle))
                .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.btn_no_shuffle));            
        }
        currentSongIdx = 0;
        play();        
    }

    //play the requested file
    private void play() {
        if (songQueue.size() > currentSongIdx && songQueue.get(currentSongIdx) != null) {
            currentSong = (Mp3File) songQueue.get(currentSongIdx);
            try {            
                mediaPlayer.reset();
                mediaPlayer.setDataSource(currentSong.file);
                mediaPlayer.prepare();
                mediaPlayer.start();
                
                ((TextView) this.findViewById(R.id.player_title)).setText(currentSong.title);
                ((TextView) this.findViewById(R.id.player_artist)).setText(currentSong.artist);
                ((TextView) this.findViewById(R.id.player_album)).setText(currentSong.album);
                ((TextView) this.findViewById(R.id.player_timeElapsed)).setText("0:00");
                
                int durMins = mediaPlayer.getDuration()/60000;
                int durSecs = (mediaPlayer.getDuration()/1000)%60;
                
                ((TextView) this.findViewById(R.id.player_timeTotal))
                        .setText(durMins + ":" + ((durSecs > 9) ? durSecs : "0" + durSecs));
                
                SeekBar seekBar = (SeekBar) this.findViewById(R.id.player_seek);	    
                seekBar.setMax(mediaPlayer.getDuration()/1000);       
                seekBar.setOnSeekBarChangeListener(this);
                
                MusicMetadataSet mp3set = new MyID3().read(new File(currentSong.file));
                
                IMusicMetadata mp3data = mp3set.getSimplified();
                
                ((ImageView) this.findViewById(R.id.player_albumImage)).setImageBitmap(null);                
    
                if (mp3data instanceof MusicMetadata && ((MusicMetadata) mp3data).getPictureList().size() > 0) {
                    try {
                        ImageData data = (ImageData) ((MusicMetadata) mp3data).getPictureList().get(0);
                        ByteArrayInputStream is = new ByteArrayInputStream(data.imageData);
                        ((ImageView) this.findViewById(R.id.player_albumImage))
                            .setImageBitmap(BitmapFactory.decodeStream(is));                    
                    } catch (Exception e) {
                        Log.e(getClass().getName(), "Album art not available for " + currentSong.file, e);                    
                    }
                }
                
                currentRating = 0;
                try {
                    currentRating = Integer.parseInt(mp3data.getComment().substring(10));
                } catch (Exception e) {
                    currentRating = 0;
                    Log.w(getClass().getName(), "Rating not available for: '" + currentSong.file + "'");
                }
                setSongRating(currentRating);
            } catch (Exception e) {
                Toast.makeText(PlaybackView.this, "Unable to play file: " + currentSong.file, Toast.LENGTH_LONG).show();  
                Log.e(getClass().getName(), "Unable to play file: " + currentSong.file, e);
            }
        }
    }
    
    private void setSongRating(int rating) {
        ((ImageView) this.findViewById(R.id.star1))
                .setImageResource((rating > 0) ? R.drawable.star : R.drawable.emptystar);
        ((ImageView) this.findViewById(R.id.star2))
                .setImageResource((rating > 1) ? R.drawable.star : R.drawable.emptystar);
        ((ImageView) this.findViewById(R.id.star3))
                .setImageResource((rating > 2) ? R.drawable.star : R.drawable.emptystar);
        ((ImageView) this.findViewById(R.id.star4))
                .setImageResource((rating > 3) ? R.drawable.star : R.drawable.emptystar);
        ((ImageView) this.findViewById(R.id.star5))
                .setImageResource((rating > 4) ? R.drawable.star : R.drawable.emptystar);
    }
    
	OnCompletionListener songCompletedListener = new OnCompletionListener(){
		@Override
		public void onCompletion(MediaPlayer mp) {
		    next();
		}
	};
    
    //update seekbar and position labels based on current song position
    private void updateSongPosition() {
        if (!seeking){
            try {
				int curMins = mediaPlayer.getCurrentPosition()/60000;
				int curSecs = (mediaPlayer.getCurrentPosition()/1000)%60;
                ((TextView) this.findViewById(R.id.player_timeElapsed))
                    .setText(curMins + ":" + ((curSecs > 9) ? curSecs : "0" + curSecs));
		        ((SeekBar) this.findViewById(R.id.player_seek))	   						
                    .setProgress(mediaPlayer.getCurrentPosition()/1000);
            } catch (Exception e) {
                Log.e(getClass().getName(), "Error in updateSongPosition", e);    
            }
        }        
    }

    //user is manually moving the seekbar    
	public void onStartTrackingTouch(SeekBar seekBar) {
		seeking = true;
	}
    
	//user is done manually moving the seekbar
	public void onStopTrackingTouch(SeekBar seekBar) {
	    try {
	        mediaPlayer.seekTo((int) (((float) seekBar.getProgress() / (float) seekBar.getMax()) * mediaPlayer.getDuration()));
	        seekBar.setProgress(seekBar.getProgress());		
	        seeking = false;
        } catch (Exception e) {
            Log.e(getClass().getName(), "Error in OnStopTrackingTouch", e);
        }	        
	}
	
	//seekbar changed event
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
	    try {
	        if (fromUser) { }
        } catch (Exception e) {
            Log.e(getClass().getName(), "Error in onProgressChanged", e);            
        }	        
	}	

    //Thread to refresh the seekbar and position labels, based on the current song position    
    protected Runnable screenRefresh = new Runnable() {
        public void run() {
            updateSongPosition();
            statusHandler.postDelayed(this, 1000);
        }
    };

    protected void onPrepareDialog(int id, Dialog dialog) {
        switch(id) {
            case 0:
                updateRating(dialog);             
                break;
            default:
                
                break;
        }
    }
    
    protected Dialog onCreateDialog(int id) {        
        switch(id) {
            case 0:
                final Dialog dialog = new Dialog(PlaybackView.this);
                dialog.setContentView(R.layout.rating_dialog);
                dialog.setTitle("Set Rating");
                
                ((ImageView) dialog.findViewById(R.id.star1))
                    .setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            currentRating = 1;
                            updateRating(dialog);
                        }
                });                
                    
                ((ImageView) dialog.findViewById(R.id.star2))
                    .setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            currentRating = 2;
                            updateRating(dialog);
                        }
                });                                    
                    
                ((ImageView) dialog.findViewById(R.id.star3))
                    .setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            currentRating = 3;
                            updateRating(dialog);
                        }
                });                                    

                ((ImageView) dialog.findViewById(R.id.star4))
                    .setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            currentRating = 4;
                            updateRating(dialog);
                        }
                });                                    

                ((ImageView) dialog.findViewById(R.id.star5))
                    .setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            currentRating = 5;
                            updateRating(dialog);
                        }
                });  

                ((Button) dialog.findViewById(R.id.btn_rating_ok))
                    .setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            changeRating();
                        }
                });  
                return dialog;
            default:
                return null;
        }
    }

    private void changeRating() {
        try {        
            File file = new File(currentSong.file);
            MusicMetadataSet mp3set = new MyID3().read(file);
            MusicMetadata mp3data = (MusicMetadata) mp3set.getSimplified();        
            mp3data.clearComment();
            mp3data.setComment("JG-Rating-" + currentRating);
            (new MyID3()).update(file, mp3set, mp3data);
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
                File ratingsFile = new File(Environment.getExternalStorageDirectory() + "/Music/modified_ratings.txt");
                if (!ratingsFile.exists()) {
                    ratingsFile.createNewFile();
                }
                BufferedWriter writer = new BufferedWriter(new FileWriter(ratingsFile, true));
                writer.write(currentSong.file + "||" + currentRating);
                writer.write("\r\n");
                writer.close();
                PlaybackView.this.dismissDialog(0);
                Toast.makeText(PlaybackView.this, "Ratings Updated", Toast.LENGTH_LONG).show();
            } else {
                throw new Exception("Media is not mounted!");   
            }
        } catch (Exception e) {
            Toast.makeText(PlaybackView.this, "Unable to write ratings file", Toast.LENGTH_LONG).show();  
            Log.e(getClass().getName(), "Unable to write ratings file", e);                    
        } 
    }
    
    private void updateRating(Dialog dialog) {
        ((ImageView) dialog.findViewById(R.id.star1))
                .setImageResource((currentRating > 0) ? R.drawable.starbig : R.drawable.emptystarbig);
        ((ImageView) dialog.findViewById(R.id.star2))
                .setImageResource((currentRating > 1) ? R.drawable.starbig : R.drawable.emptystarbig);
        ((ImageView) dialog.findViewById(R.id.star3))
                .setImageResource((currentRating > 2) ? R.drawable.starbig : R.drawable.emptystarbig);
        ((ImageView) dialog.findViewById(R.id.star4))
                .setImageResource((currentRating > 3) ? R.drawable.starbig : R.drawable.emptystarbig);
        ((ImageView) dialog.findViewById(R.id.star5))
                .setImageResource((currentRating > 4) ? R.drawable.starbig : R.drawable.emptystarbig);                 
    }
    
    private void updateTitle() {
        this.setTitle(this.getTitle() + " - " + songQueue.size() + " song(s)");
    }

    @Override
    public void onBackPressed() {
        Intent intent =
            new Intent(PlaybackView.this.getApplication(),
                                MenuView.class);
            startActivity(intent);
        
    }
    
    @Override
    protected void onUserLeaveHint() {
        //End the application if the user navigates away (home screen)
        super.onUserLeaveHint();
        finish();
    }       
       
    @Override
    protected void onStop() {
        //End the application if another application takes focus
        super.onStop();
        finish();
    }
        
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }            
            mediaPlayer.release();
            mediaPlayer = null;
        }
        statusHandler.removeCallbacks(screenRefresh);
    }    
}
